package com.shengyijie.activity.tab;

import java.util.ArrayList;

import org.apache.http.HttpResponse;
 
import com.shengyijie.activity.R;     
import com.shengyijie.activity.commen.ItemListActivity;
import com.shengyijie.adapter.viewadapter.CategoryListAdapter;
import com.shengyijie.context.ContextApplication;
import com.shengyijie.model.http.HttpConnectApi; 
import com.shengyijie.model.json.JsonParser;
import com.shengyijie.model.object.Listobject.ProPictureList;
import com.shengyijie.model.object.Listobject.ProjectList;
import com.shengyijie.model.object.Listobject.PushMessageList;
import com.shengyijie.model.object.baseobject.Category;      
import com.shengyijie.model.object.baseobject.Project;
import com.shengyijie.model.object.baseobject.PushMessage;
import com.shengyijie.model.object.baseobject.User;

import android.app.Activity; 
import android.app.AlertDialog;
import android.app.ProgressDialog; 
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnKeyListener;
import android.os.AsyncTask;
import android.os.Bundle; 
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener; 
import android.widget.AdapterView; 
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class CategoryActivity extends Activity implements OnClickListener{
   
	private ListView categoryListView;
	private CategoryListAdapter listAdapter;
	private TextView tv_no;
	private View preView=null;
	private int preTask=0;
	public Task task;
	private HttpConnectApi httpConnect;
	private User user;
	
	public ArrayList<Category> categoryList=new ArrayList<Category>(); ;
	
    public void onCreate(Bundle savedInstanceState){
         super.onCreate(savedInstanceState);
         setContentView(R.layout.category);
         initView();
         getCategoryList();
          
        // doCheckEmail();
//         doLogin();
        // doGetLoginUser();
//         doGetPushMessage(); 
//         doGetAttentionProject();
//         doGetFindIndustry();
//         doGetRecommendedList();
//         doGetProjectDetail();
//         //doGetProPicList();
//         //doGuestBook();
//        // doAttentionPro();
//         doGetMessageProject();
    }
    
    
    
    
    public String doCheckEmail(){
    	String result="email_fail";
        httpConnect=HttpConnectApi.getInstance();
        try {
            HttpResponse response=httpConnect.getCheckEmail("liukun@yuele.com");
            if (response.getStatusLine().getStatusCode() == 200)
			{ 
           	    JsonParser jsonParser=JsonParser.getInstance();
           	    if(jsonParser.getResultCode(response)==ContextApplication.RESULT_CODE_OK) 
           	    	result="email_ok";
           	    else if(jsonParser.getResultCode(response)==ContextApplication.RESULT_CODE_1000) 
       	    	    result="email_had";
			}
            return result;
        }catch (Exception e) {} 
		return result;
 }
    
    public String doLogin(){
    	String result="login_fail";
        httpConnect=HttpConnectApi.getInstance();
        try {
        	 
            HttpResponse response=httpConnect.doLogin("qqqq@qqq.qq", "111111");
            if (response.getStatusLine().getStatusCode() == 200)
			{ 
           	    JsonParser jsonParser=JsonParser.getInstance();
           	     user=jsonParser.getRegister(response);
           	    if(user.getState()==ContextApplication.RESULT_CODE_OK){
           	    	result="login_ok";
           	    }else if(user.getState()==ContextApplication.RESULT_CODE_1001){
           	    	result="login_name_fail";
           	    }else if(user.getState()==ContextApplication.RESULT_CODE_1002){
           	    	result="login_password_fail";
           	    }
			}
            return result;
        }catch (Exception e) {} 
		return result;
 }
    
    public String doGetLoginUser(){
    	String result="login_fail";
        httpConnect=HttpConnectApi.getInstance();
        try {
        	 
            HttpResponse response=httpConnect.getLoginUser(user.getSession_ID());
            if (response.getStatusLine().getStatusCode() == 200)
			{ 
           	    JsonParser jsonParser=JsonParser.getInstance();
           	    user=jsonParser.getLoginUser(response);
           	    if(user.getState()==ContextApplication.RESULT_CODE_OK){
           	    	result="login_ok";
           	    }else if(user.getState()==ContextApplication.RESULT_CODE_1001){
           	    	result="login_name_fail";
           	    }else if(user.getState()==ContextApplication.RESULT_CODE_1002){
           	    	result="login_password_fail";
           	    }
			}
            return result;
        }catch (Exception e) {} 
		return result;
   }
    PushMessageList pushMessageList;
    public String doGetPushMessage(){
    	String result="message_fail";
        httpConnect=HttpConnectApi.getInstance();
        try { 
            HttpResponse response=httpConnect.getFindManage(user.getSession_ID(),"0,15");
            if (response.getStatusLine().getStatusCode() == 200)
			{ 
           	    JsonParser jsonParser=JsonParser.getInstance();
           	    pushMessageList=jsonParser.getPushMessage(response);
           	    if(pushMessageList!=null){
           	    	if(pushMessageList.getCount()>0)
           	    	    result="message_ok";
           	    	else if(pushMessageList.getCount()==0)
           	    		result="message_0";
           	    } 
			}
            return result;
        }catch (Exception e) {} 
		return result;
   }
    
    
    
    
    ProjectList projectList;
    public String doGetAttentionProject(){
     	String result="at_fail";
        httpConnect=HttpConnectApi.getInstance();
        try { 
            HttpResponse response=httpConnect.getAttentionProject(ContextApplication.user.getSession_ID(),"0,50");
            if (response.getStatusLine().getStatusCode() == 200)
			{ 
           	    JsonParser jsonParser=JsonParser.getInstance();
           	    projectList=jsonParser.getAttentionProgect(response);
           	    if(projectList!=null){
           	    	if(projectList.getCount()>0)
           	    	    result="at_ok";
           	    	else if(projectList.getCount()==0)
           	    		result="at_0";
           	    } 
			}
            return result;
        }catch (Exception e) {} 
		return result;
   }
    
//    public String doGetFindIndustry(){
//     	String result="in_fail";
//        httpConnect=HttpConnectApi.getInstance();
//        try { 
//            HttpResponse response=httpConnect.getFindIndustry(ContextApplication.user.getSession_ID(),"7","0,5");
//            if (response.getStatusLine().getStatusCode() == 200)
//			{ 
//           	    JsonParser jsonParser=JsonParser.getInstance();
//           	    projectList=jsonParser.getAttentionProgect(response);
//           	    if(projectList!=null){
//           	    	if(projectList.getCount()>0)
//           	    	    result="in_ok";
//           	    	else if(projectList.getCount()==0)
//           	    		result="in_0";
//           	    } 
//			}
//            return result;
//        }catch (Exception e) {} 
//		return result;
//   }
    
    public String doGetRecommendedList(){
     	String result="re_fail";
        httpConnect=HttpConnectApi.getInstance();
        try { 
            HttpResponse response=httpConnect.getRecommendedList("0,50");
            if (response.getStatusLine().getStatusCode() == 200)
			{ 
           	    JsonParser jsonParser=JsonParser.getInstance();
           	    projectList=jsonParser.getAttentionProgect(response);
           	    if(projectList!=null){
           	    	if(projectList.getCount()>0)
           	    	    result="re_ok";
           	    	else if(projectList.getCount()==0)
           	    		result="re_0";
           	    } 
			}
            return result;
        }catch (Exception e) {} 
		return result;
   }
    
    
    Project project;
    public String doGetProjectDetail(){
     	String result="pr_fail";
        httpConnect=HttpConnectApi.getInstance();
        try { 
            HttpResponse response=httpConnect.getProjectDetail(projectList.getItem(0).getID());
            if (response.getStatusLine().getStatusCode() == 200)
			{ 
           	    JsonParser jsonParser=JsonParser.getInstance();
           	    project=jsonParser.getProgectDetail(response);
           	    if(project!=null){ 
           	    	 result="pr_ok"; 
           	    } 
			}
            return result;
        }catch (Exception e) {} 
		return result;
   }
    ProPictureList proPictureList;
    public String doGetProPicList(){
     	String result="pp_fail";
        httpConnect=HttpConnectApi.getInstance();
        try { 
            HttpResponse response=httpConnect.getProjectPic(projectList.getItem(0).getID());
            if (response.getStatusLine().getStatusCode() == 200)
			{ 
           	    JsonParser jsonParser=JsonParser.getInstance();
           	    proPictureList=jsonParser.getProPicList(response);
           	    if(proPictureList!=null){
           	    	if(proPictureList.getCount()>0)
           	    	    result="pp_ok";
           	    	else if(proPictureList.getCount()==0)
           	    		result="pp_0";
           	    } 
			}
            return result;
        }catch (Exception e) {} 
		return result;
   }
    

    
    public String doGetMessageProject(){
     	String result="mp_fail";
        httpConnect=HttpConnectApi.getInstance();
        try { 
            HttpResponse response=httpConnect.getMessageProject(ContextApplication.user.getSession_ID(),"0,50");
            if (response.getStatusLine().getStatusCode() == 200)
			{ 
           	    JsonParser jsonParser=JsonParser.getInstance();
           	    projectList=jsonParser.getAttentionProgect(response);
           	    if(projectList!=null){
           	    	if(projectList.getCount()>0)
           	    	    result="mp_ok";
           	    	else if(projectList.getCount()==0)
           	    		result="mp_0";
           	    } 
			}
            return result;
        }catch (Exception e) {} 
		return result;
   }
    
    
    public void initView(){
    	 categoryListView=(ListView) this.findViewById(R.id.categorylist); 
    	 categoryListView.setOnItemClickListener(itemClickListener);
    	 tv_no=(TextView) this.findViewById(R.id.no);
    	 tv_no.setVisibility(View.INVISIBLE); 
    	 
    	 mypDialog=new ProgressDialog(this);//实例化
         mypDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); 
         mypDialog.setIndeterminate(false);//设置ProgressDialog 的进度条是否不明确
         mypDialog.setCancelable(false);//设置ProgressDialog 是否可以按退回按键取消
         mypDialog.setOnKeyListener(new DialogOnKeyListener());
    }
    
    public class DialogOnKeyListener implements OnKeyListener {
		public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
			if (keyCode == KeyEvent.KEYCODE_BACK) {
				try{
				  mypDialog.hide();
				  if(task.getStatus()==AsyncTask.Status.RUNNING){
		    		 task.cancel(true);
		    		 
				  }
			    }catch(Exception e){}
			 }
			return true;
		}
    }
    
    public void getShopList(){
   	     try{
   		      tv_no.setVisibility(View.INVISIBLE);  
			  preTask=1;
			  task=new Task();
			  task.execute(TASK_LOAD_ITEM_LIST);
   	    }catch(Exception e){}
	}
    
    public OnItemClickListener itemClickListener = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> parent, View view,
				int position, long id) {
			try{
				 preView=view;  
	    		 Category content=(Category)parent.getItemAtPosition(position);
	    		 ContextApplication.itemName=content.getName();
	    		 ContextApplication.industry_id=content.getID();
	    		 changeToItemActivity();
//				 preTask=2;
//		    	 task=new Task();  
//    		     task.execute(TASK_LOAD_ITEM_LIST); 
				 
			}catch(Exception e){}
		}
    };
    boolean isFirstStart=true;
    protected void onResume() {
	      super.onResume();
	      try{
	    	  if(!isFirstStart){
		          
		      }
	    	  isFirstStart=false;
	      }catch(Exception e){}
	 }
    
    

	@Override
	public void onClick(View v) { 
		
	}
	
	 public void changeToItemActivity(){
		 ContextApplication.prePage=ContextApplication.PAGE_CATEGORY; 
		 Intent intent=new Intent();
		 intent.setClass(this, ItemListActivity.class);
		 this.startActivityForResult(intent,1);
	}
	
	 
//	 public String getShops(){ 
//	    	String result="allshop_fail"; 
//	         httpConnect=HttpConnectApi.getInstance();
//	         ShopBriefList shopBriefList=null;
//	         try { 
//	             HttpResponse response=httpConnect.getChannel( );
//	             if (response.getStatusLine().getStatusCode() == 200)
//	 			 {           	
//	            	    JsonParser jsonParser=JsonParser.getInstance();
//	            	    shopBriefList=jsonParser.getChannel(response);  
//	            	    if (shopBriefList!=null) {
//	        	    	     contentList.clear();
//	    					 for(int i=0;i<shopBriefList.getCount();i++){
//	    						    ListContent content = new ListContent(); 
//	    							content.setId(shopBriefList.getItem(i).getId()+""); 
//	    						    content.setImageUrl(HttpConnectApi.IMG_SHOP_URL+shopBriefList.getItem(i).getImageUrl());  
//	    							content.setTile(shopBriefList.getItem(i).getName());
//	    							content.setDes(shopBriefList.getItem(i).getLastCoupon());
//	    							content.setDistance(shopBriefList.getItem(i).getDistance());
//	    							 
//	    							contentList.add(content);
//	    					 }
//	    					 listAdapter = new shoplistAdapter(this, contentList, shopList, 4,true); 
//	    	        			
//	    	        		 if(contentList.size()>0){
//	    	        				result = "allshop_success";
//	    	        		 }else if(contentList.size()==0){ 
//	    	        				result = "allshop_0";
//	    	        		 } 
//	            	    }
//	            	    jsonParser=null;  
//	 			 }
//	             response=null;
//	             httpConnect=null;
//	         }         
//	 		catch (Exception e) {		
//	 		} 
//	 		return result; 
//	    }
	 
	 public String getItemList(){ 
 	       String result="item_ok"; 
 	       int i=0;
           while(i<100){
        	   i++;
           } 
		   return result; 
     }
	 
	 public void getCategoryList(){   
		    Category content=null;
		    content= new Category(); 
			content.setID(1); 
		    content.setImageUrl("category1");  
			content.setName("服饰箱包");  
			categoryList.add(content);
			  
			content= new Category(); 
			content.setID(2); 
		    content.setImageUrl("category2");  
			content.setName("美容保健");  
			categoryList.add(content);
			
			content= new Category(); 
			content.setID(3); 
		    content.setImageUrl("category3");  
			content.setName("美酒饮料");  
			categoryList.add(content);
			
			content= new Category(); 
			content.setID(4); 
		    content.setImageUrl("category4");  
			content.setName("家居环保");  
			categoryList.add(content);
			
			content= new Category(); 
			content.setID(5); 
		    content.setImageUrl("category5");  
			content.setName("餐饮娱乐");  
			categoryList.add(content);
			
			content= new Category(); 
			content.setID(6); 
		    content.setImageUrl("category6");  
			content.setName("教育培训");  
			categoryList.add(content);
			
			content= new Category(); 
			content.setID(7); 
		    content.setImageUrl("category7");  
			content.setName("新锐创意");  
			categoryList.add(content);
					  
			listAdapter = new CategoryListAdapter(this, categoryList, categoryListView);  
			categoryListView.setAdapter(listAdapter);
	}
	 
     private ProgressDialog mypDialog;
     
      
     
     private final static int ALERT_NO_CONNECT=0; 
	 private final static int ALERT_LOADING=1;
	 
	 private final static int RESULT_LOAD_ITEMLIST_OK=2;
	 private final static int RESULT_LOAD_ITEMLIST_0=3; 
	 private final static int RESULT_LOAD_ITEMLIST_FAIL=4;
	   
	 
	 
	  
	 
	// private final static String TASK_LOAD_LIST="loadlist";
	 private final static String TASK_LOAD_ITEM_LIST="loaditemlist";   
	 private final Handler handler = new Handler(Looper.getMainLooper()) {
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
			 	switch (msg.what) { 
				   case ALERT_LOADING:
					    mypDialog.setMessage("数据载入中...");
					    mypDialog.show();
					    break;
				   case RESULT_LOAD_ITEMLIST_FAIL:
					   try{
					      mypDialog.hide();
			              new AlertDialog.Builder(CategoryActivity.this)   
			                .setTitle("对不起")
			                .setMessage("无法获取数据！")
			                .setPositiveButton("确定", null)
			                .show();
			              categoryListView.setAdapter(null);
			              tv_no.setVisibility(View.VISIBLE);
					    }catch(Exception e){}
					     break;
				   case RESULT_LOAD_ITEMLIST_0:
					     mypDialog.hide(); 
					     break; 
                    case RESULT_LOAD_ITEMLIST_OK:
                    	try{
	                    	 mypDialog.hide(); 
	                    	 changeToItemActivity();
                    	 }catch(Exception e){}
					     break; 
				}
			}
		};
		
		
	private class Task extends AsyncTask<String, String, String> {
 
		@Override
		protected String doInBackground(String... params) {
			if(params[0].equals(TASK_LOAD_ITEM_LIST)){
				return getItemList();
			}else
			    return ""; 
		} 
		@Override
		protected void onPostExecute(String result) {				
			super.onPostExecute(result);

			if(result.equals("item_fail")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOAD_ITEMLIST_FAIL;
				handler.sendMessage(msg);
			}else if(result.equals("item_ok")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOAD_ITEMLIST_OK;
				handler.sendMessage(msg);
			}else if(result.equals("item_0")){
				Message msg = Message.obtain();
				msg.what = RESULT_LOAD_ITEMLIST_0;
				handler.sendMessage(msg);
			}   
		} 
		@Override
		protected void onPreExecute() { 
			super.onPreExecute();
			if( preTask==1||preTask==2){
			   Message msg = Message.obtain();
			   msg.what = ALERT_LOADING;
			   handler.sendMessage(msg);
			}
		} 
		@Override
		protected void onProgressUpdate(String... values) {
			super.onProgressUpdate(values);
		}
	}
	public boolean onKeyDown(int keyCode,KeyEvent event) {   
	    if (keyCode == KeyEvent.KEYCODE_BACK) { 
	    	
				 new AlertDialog.Builder(this).setTitle("提示")
				 .setMessage("确定退出？")
				 .setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) { 
						android.os.Process.killProcess(android.os.Process.myPid());
					}
				  })
				  .setNegativeButton("取消", new DialogInterface.OnClickListener() {
					    public void onClick(DialogInterface dialog, int whichButton) {
					     }
				  })
				  .show();
	    	
	         return true;   
	     } else
	         return super.onKeyDown(keyCode,event);   
	 }
    
}